package com.xs.jmb2c.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xs.jmb2c.dto.AdminLoginDTO;
import com.xs.jmb2c.entity.Admin;
import com.xs.jmb2c.exceptions.BusinessException;
import com.xs.jmb2c.mapper.AdminMapper;
import com.xs.jmb2c.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.jmb2c.utils.JwtUtil;
import com.xs.jmb2c.vo.AdminLoginVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-07-07
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private WxMaService wxMaService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {
        Admin admin = null;
        //账号登录
        if(adminLoginDTO.getEmail() != null){
            LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Admin::getEmail,adminLoginDTO.getEmail());
            admin = this.getOne(wrapper);
            if (admin == null) {
                log.info("账号不存在");
                throw new BusinessException("账号不存在或密码错误");
            }
            log.info("密码密文:{}",passwordEncoder.encode(adminLoginDTO.getPassword()));
            if(!passwordEncoder.matches(adminLoginDTO.getPassword(),admin.getPassword())){           //!member.getPassword().equals(memberLoginDTO.getPassword())
                log.info("密码错误");
                throw new BusinessException("账号不存在或密码错误");
            }
        }
        //  管理员后台无微信登录
        //3.签发token
        HashMap<String,Object> map = new HashMap<>();
        map.put("id",admin.getId());
        String token = jwtUtil.generateToken(map);

        AdminLoginVO adminLoginVO = new AdminLoginVO();
        adminLoginVO.setToken(token);
        adminLoginVO.setAvatar(admin.getAvatar());
        return adminLoginVO;
    }
}
